package bibliotheque.server;

import bibliotheque.wave.WaveAction;
import bibliotheque.wave.WaveAgent;

public class HelloAction extends WaveAction {
    
    private long timeout;
    
    public HelloAction(long timeout) {
        this.timeout = timeout;
    }
    
    public void PropagateBefore(WaveAgent agent) throws Exception {
        if (agent instanceof Server) {
            Server server = (Server)agent;
            try {
                server.mutex.acquireUninterruptibly();
                if(server.state == Server.State.STOP) throw new Exception("Hello failed cause server state is stopped.");
                if(server.state == Server.State.SUBSCRIBING) {
                    server.state = Server.State.STARTING;
                    server.StateChanged(server.state.toString());
                } else {
                    server.timertask_hellotimeout.cancel();
                    if(server.state == Server.State.STARTING) {
                        server.state = Server.State.START;
                        server.StateChanged(server.state.toString());
                    }
                }
                if(server.timertask_hellotimeout != null) server.timertask_hellotimeout.cancel();
                server.timertask_hellotimeout = server.new TimertaskHelloTimeout();
                server.timer_hellotimeout.schedule(server.timertask_hellotimeout, timeout);
            } catch (Exception ex) {
                server.ErrorOccured(ex.getMessage());
                throw ex;
            } finally {
                server.mutex.release();
            }
        }
    }
    
    public void GlobalEnd(WaveAgent agent) throws Exception {
        if (agent instanceof Server) {
            Server server = (Server)agent;
            try {
                server.mutex.acquireUninterruptibly();
                if(server.state == Server.State.SUBSCRIBING) throw new Exception("HelloFinish failed cause server state is subscribing.");
                if(server.state == Server.State.STOP) throw new Exception("HelloFinish failed cause server state is stopped.");
                try {
                    server.name_server.Hello();
                } catch (Exception ex) {
                    throw new Exception("Hello failed cause the nameserver returned an error.");
                }
            } catch (Exception ex) {
                server.ErrorOccured(ex.getMessage());
                throw ex;
            } finally {
                server.mutex.release();
            }
        }
    }
}
